package com.yifi.module.jwflow.controller;

import cn.hutool.core.util.IdUtil;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yifi.common.base.BaseController;
import com.yifi.common.plugins.JwFlowPlugin;
import com.yifi.common.utils.DbUtils;
import com.yifi.common.utils.ToolSession;
import io.gitee.yaoshanli.engine.model.WfTaskModel;

@Path(value="/flow_demo",viewPath = "/jwflow/")
public class flow_demo_controller extends BaseController {

    public void index() {
        String id = getPara("id", "");
        set("id", id);
        render("flow_demo.html");
    }

    public void getData()
    {
        String id = getPara("id", "");

        String sql="select * from jw_flow_demo where id='"+id+"'";
        Record record = Db.findFirst(sql);

        renderJson(record);
    }

    public void save()
    {
        String id=getPara("id","");
        String title=getPara("title","");
        String content=getPara("content","");

        String wfcode="test";   //流程代码

        String sql="select * from jw_flow_demo where id='"+id+"'";
        Record record = Db.findFirst(sql);
        boolean isedit=true;
        if(record==null)
        {
            isedit=false;
            record = new Record();
            id=IdUtil.fastUUID();
            record.set("id", id);
        }
        record.set("title", title);
        record.set("content", content);
        if(DbUtils.save("jw_flow_demo","id",record,isedit))
        {
            String wfid=JwFlowPlugin.getEngine().flow().getWfCode(wfcode).getId();
            String user= ToolSession.getUser(this).getCcode();
            String dept=ToolSession.getUser(this).getCdept();
            WfTaskModel wfTaskModel =JwFlowPlugin.getEngine().task().startTask(id,wfid,user,title,content,dept);
            if(wfTaskModel!=null)
            {
                renderJson(success("成功"));
            }
            else
            {
                renderJson(error("流程失败"));
            }
        }
        else
        {
            renderJson(error("失败"));
        }
    }
}
